var express = require('express');
var bodyParser = require('body-parser');
var routes = require('./routes');
var ParseServer = require('parse-server').ParseServer;
var ParseDashboard = require('parse-dashboard');
var path = require('path');
var util = require('util');

//环境确认,用于开发过程中的环境切换
var HOST = '120.55.114.198';
//数据库服务连接,配置数据库连接使用
var databaseUri = 'mongodb://'+ HOST +':4000/parse';

//debug环境确认设置,打开debug会记录每次网络请求
var debug = false;
//确认默认的数据库连接,若没有设置数据库连接,将使用默认连接
if (!databaseUri) {
  console.log('DATABASE_URI not specified, falling back to localhost.');
}

//Express框架的parseServer的配置,所有服务基于此处配置
var api = new ParseServer({
    databaseURI: databaseUri || 'mongodb://parse_admin:parse@' + HOST+':4000/parse',
    cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
    appId: process.env.APP_ID || 'myAppId',
    masterKey: process.env.MASTER_KEY || 'masterKey',
    serverURL: process.env.SERVER_URL || 'http://'+HOST+':1337/parse',
    liveQuery: {
    classNames: ["Posts", "Comments"]
    },
    push: {
        android: {
            masterKey: '92ccd4aa96f4264e7c12ede7',
            apiKey: '835a16b9363e6b85d7ea75ed'
        },
        ios: [{
            pfx: 'keys/development_push_dzpy.p12',
            passphrase: 'dzpy', // optional password to your p12/PFX
            bundleId: 'com.lovepinyao.dzpy',
            production: false
        },{
            pfx: 'keys/production_push_dzpy.p12',
            passphrase: 'dzpy', // optional password to your p12/PFX
            bundleId: 'com.lovepinyao.dzpy',
            production: true
        }]
    }
});

//Parse-dashboard的配置窗口,用于开发监控数据走向
var dashboard = new ParseDashboard({
    "apps": [{
        "serverURL": "http://"+HOST+":1337/parse",
        "appId": "myAppId",
        "masterKey": "masterKey",
        "appName": "localData"
    },{
        "serverURL": "http://120.26.134.103:1337/parse",
        "appId": "myAppId",
        "masterKey": "masterKey",
        "appName": "TestData"
    },{
        "serverURL": "https://parse.lovepinyao.com/parse",
        "appId": "myAppId",
        "masterKey": "masterKey",
        "appName": "OnlineData"
    }],
    "users": [
        {
            "user":"xiaojun",
            "pass":"xiaojun"
        },
        {
            "user":"wuliao",
            "pass":"wuliao"
        },
        {
            "user":"taoyingjun",
            "pass":"taoyingjun"
        }]
    },
    true);
//确定node的运行环境为开发环境
process.env.NODE_ENV = 'production';
//初始化express对象
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//dashboard的路由配置,放在debug之前,无需答应对应log
app.use('/dashboard', dashboard);
//捕获所有的网络请求,打印到access.log
if(debug){
    app.all('*',function(req,res,next){
        console.log('[' + new Date().toString() + ']: ' + req.method + ' ' + req.url + ' body:' + req.body);
        next();
    });
}
//默认页面,可以考虑驱动到对应的网站系统
routes(app);
//将静态文件访问确定到public文件夹
app.use('/public', express.static(path.join(__dirname, '/public')));
//确定parse服务的url路径,后期可以用来区分版本
var mountPath = process.env.PARSE_MOUNT || '/parse';
app.use(mountPath, api);

//错误捕捉函数,用来捕捉错误异常,记录到文件系统
app.use(function(err, req, res, next) {
    console.log('[' + new Date().toString() + ']: ' + req.method + ' ' + req.url);
    console.log(util.inspect(err,true,null,true));
    res.status = 500;
    next("Internal Error");
});

var port = process.env.PORT || 1337;
var httpServer = module.exports  =require('http').createServer(app);
var httpServer1 = module.exports  =require('http').createServer(app);
var httpServer2 = module.exports  =require('http').createServer(app);
var httpServer3 = module.exports  =require('http').createServer(app);

if(!module.parent){
    httpServer.listen(port, function() {
        console.log('parse-server-example running on port ' + port + '.');
    });
    httpServer1.listen(1338, function() {
        console.log('parse-server-example running on port   1338 ');
    });
    httpServer2.listen(1339, function() {
        console.log('parse-server-example running on port   1339 ');
    });
    httpServer3.listen(1340, function() {
        console.log('parse-server-example running on port   1340 ');
    });
}

ParseServer.createLiveQueryServer(httpServer);
